/*
 * @Description: 在组件内部注册的全局事件，组件销毁时跟随销毁
 * @Author: bxsdhx
 * @Date: 2024-01-18 13:45:45
 * @LastEditTime: 2024-07-12 17:58:15
 * Copyright (C) 2024 bxsdhx. All rights reserved.
 */
import { onBeforeUnmount } from "vue";
import hxzxUtils from "hxzx-utils";

interface EventBus {}

export default {
  /**
   * @description: 组件级别的document.addEventListener
   * @return {void}
   */
  addEventListener<K extends keyof DocumentEventMap>(
    type: K,
    listener: (this: Document, ev: DocumentEventMap[K]) => any,
    options?: boolean | AddEventListenerOptions
  ): void {
    document.addEventListener(type, listener, options);
    onBeforeUnmount(function () {
      document.removeEventListener(type, listener, options);
    });
  },
  /**
   * @description: 组件级别的document.removeEventListener
   * @return {void}
   */
  removeEventListener: document.removeEventListener,
  /**
   * @description: 组件级别的eventBus.on
   * @param {string} id 订阅ID
   * @param {function} listener 订阅事件
   * @return {void}
   */
  on<K extends keyof EventBus>(id: K, listener: EventBus[K]): void {
    hxzxUtils.eventBus.on(id, listener);
    onBeforeUnmount(function () {
      hxzxUtils.eventBus.off(id, listener);
    });
  },
  /**
   * @description: 组件级别的eventBus.emit
   * @param {string} id 订阅ID
   * @return {void}
   */
  emit<K extends keyof EventBus>(
    id: K,
    ...args: EventBus[K] extends (...args: infer P) => any ? P : never
  ): void {
    hxzxUtils.eventBus.emit(id, ...args);
  },
  /**
   * @description: 组件级别的快捷键
   * @param {string} key 快捷键
   * @param {function} listener 事件
   * @return {void}
   */
  shortcutKeys(key: string, listener: (event: KeyboardEvent) => void): void {
    hxzxUtils.eventBus.on(key, listener);
    onBeforeUnmount(function () {
      hxzxUtils.eventBus.off(key, listener);
    });
  },
};
